package renguanyu.app.auth4fx.controller.user;

import javafx.concurrent.Task;
import renguanyu.app.auth4fx.App;
import renguanyu.app.auth4fx.model.user.UserDto;
import renguanyu.app.auth4fx.service.user.UserService;
import renguanyu.app.auth4fx.view.user.UserListView;

import java.util.List;
import java.util.stream.Collectors;

public class UserInfoDeleteController extends Task<Void> {

    private UserListView userListView;
    public UserInfoDeleteController(UserListView userListView) {
        this.userListView = userListView;
    }

    public void startAsyncDelete() {
        System.out.println("UserInfoDelete.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private Integer affectedRows = 0;
    @Override
    protected Void call() {
        System.out.println("UserInfoDelete.call");
        UserDto userDto = buildUserDto();
        affectedRows = UserService.deleteUser(userDto);
        return null;
    }

    private UserDto buildUserDto() {
        List<String> ids = userListView.selectedUserList.stream().map(
            user -> user.getId().toString()
        ).collect(Collectors.toList());
        UserDto userDto = new UserDto();
        userDto.setIds(ids);
        return userDto;
    }

    @Override
    protected void running() {
        System.out.println("UserInfoDelete.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("UserInfoDelete.succeeded");
        if(affectedRows >= 1){
            App.mainView.setCenter(new UserListView());
        }
    }

    @Override
    protected void failed() {
        System.out.println("UserInfoDelete.failed");
    }
}
